package cn.wolfcode.crm.service.impl;


import cn.wolfcode.crm.domain.*;
import cn.wolfcode.crm.mapper.ProductStockMapper;
import cn.wolfcode.crm.mapper.StockIncomeBillMapper;
import cn.wolfcode.crm.mapper.StockincomeMapper;
import cn.wolfcode.crm.query.ProductQueryObejct;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IStockincomeService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.krb5.internal.PAData;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class StockincomeServiceImpl implements IStockincomeService{

    @Autowired
    private StockincomeMapper incomeMapper;

    @Autowired
    private StockIncomeBillMapper billMapper;

    @Autowired
    private ProductStockMapper productStockMapper;

    public PageResult queryForList(QueryObject qo){

        List<Stockincome> list = incomeMapper.queryForList(qo);

        return new PageResult(list.size(),list);

    }

    //删除入库单
    public void delete(Long id) {
        //删除入库单之前需要先判断状态是否是入库状态
        Stockincome income = incomeMapper.selectByPrimaryKey(id);
        if(income.getState() == 1){
            //入库状态
            //需要减少库存
            List<StockIncomeBill> bills = income.getBills();
            for(StockIncomeBill bill : bills){
                //1.先获取库存
                ProductStock stock = productStockMapper.selectStockByProductSnAndDepotId(bill.getProduct().getProductName(),income.getDepot().getId());
                //如果库存不存在
                if (stock == null){
                    //删除入库明细单
                    for(Integer i = 0;i<income.getBills().size();i++){
                        billMapper.deleteByBillId(income.getId());

                    }

                    //删除入库单
                    incomeMapper.deleteByPrimaryKey(id);
                }else{
                    stock.setNumber(stock.getNumber().subtract(bill.getNumber()));
                    stock.setCostPrice(bill.getCostPrice());
                    stock.setAmountPrice(bill.getCostPrice().multiply(bill.getNumber()).setScale(2,RoundingMode.HALF_UP));
                    productStockMapper.updateProductStockNumber(stock);
                }
            }

        }
        try {
            //删除入库明细单
            for(Integer i = 0;i<income.getBills().size();i++){
                billMapper.deleteByBillId(income.getId());

            }

            //删除入库单
            incomeMapper.deleteByPrimaryKey(id);

        }catch (Exception e){
            e.printStackTrace();
        }


    }

    public PageResult getStockById(Long id) {
        List<Stockincome> list = incomeMapper.getStockById(id);
        return new PageResult(list.size(),list);
    }

    //保存
    public void save(Stockincome income) {
        //1.设置单据的业务时间，状态，操作员
        System.out.println("income"+income);
        income.setVdate(new Date());
        income.setState(Stockincome.STATE_NOMAL);
        income.setInputTime(new Date());
        //设置编码
        income.setSn(UUID.randomUUID().toString());
        //2.遍历，迭代出计算数量，单价，总金额。
        BigDecimal number = BigDecimal.ZERO;
        BigDecimal costPrice = BigDecimal.ZERO;
        BigDecimal totalPrice = BigDecimal.ZERO;
        System.out.println(income);
        for (StockIncomeBill bill : income.getBills()) {
            number = number.add(bill.getNumber());
            totalPrice = totalPrice.add(costPrice.multiply(number).setScale(2,RoundingMode.HALF_UP));
            costPrice = costPrice.add(bill.getAmountPrice().divide(bill.getNumber()));
            System.out.println(bill);
        }
        //设置
        income.setCostPrice(costPrice);
        income.setNumber(number);
        income.setAmountPrice(income.getCostPrice().multiply(income.getNumber().setScale(2,RoundingMode.HALF_UP)));
        income.setReceipts(totalPrice);

        //插入单据
        try {

            incomeMapper.insert(income);
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            //保存明细
            for(StockIncomeBill bill : income.getBills()){
                //设置billiD
                bill.setSupplier(income.getSupplier());
                bill.setBillId(income.getId());
                billMapper.insert(bill);
            }
        }catch (Exception e){
            e.printStackTrace();
        }




    }

    public PageResult getStockList() {
        List<Stockincome> list = incomeMapper.selectAll();
        return new PageResult(list.size(),list);
    }

    public void audit(Long id) {

        System.out.println(id);
        //1.获取单据
        Stockincome income = incomeMapper.selectByPrimaryKey(id);
        System.out.println(income);
        //2.判断是否是待入库状态
        if (income.getState() == Stockincome.STATE_NOMAL){
            //设置状态
            income.setState(Stockincome.STATE_LOCK);
            //更新单据状态
            incomeMapper.updateState(income);
            //2.通过商品和仓库去库存中查是库存
            System.out.println(income.getBills().size());
            System.out.println(income);
            for(StockIncomeBill bill:income.getBills()){

                ProductStock stock1 = productStockMapper.selectStockByProductSnAndDepotId(bill.getProduct().getProductName(),income.getDepot().getId());
                    ProductStock stock = new ProductStock();
                System.out.println(stock);
                if(stock1 == null){//仓库中没有
                    //设置库存
                    //商品编号
                    stock.setSn(income.getSn());
                   //入库时间
                    stock.setInputTime(new Date());
                    //库存数量
                    stock.setNumber(income.getNumber());
                    //小计
                    stock.setAmountPrice(income.getAmountPrice());
                    //实收
                    stock.setReceipts(income.getReceipts());
                    //单价
                    stock.setCostPrice(income.getCostPrice());
                    //供应商
                    stock.setSupplier(income.getSupplier());
                    //商品
                    stock.setProduct(bill.getProduct());
                    //仓库
                    stock.setDepot(income.getDepot());
                    //操作员
                    stock.setOperator(income.getOperator());
                    //插入库存
                    System.out.println("stock==="+stock);
                    productStockMapper.insert(stock);
                }else{
                    BigDecimal number = stock1.getNumber();
                    BigDecimal amountPrice = stock1.getAmountPrice();
                    number = number.add(bill.getNumber());
                    stock1.setNumber(number);
                    amountPrice = amountPrice.add(bill.getAmountPrice());
                    stock1.setAmountPrice(stock1.getNumber().multiply(stock1.getCostPrice()));
                    System.out.println(amountPrice);
                    //更新库存数量
                    productStockMapper.updateProductStockNumber(stock1);
                }

            }
        }else {
            throw new RuntimeException("当前已经是入库状态，不需要入库");
        }
    }

    public PageResult getBillList() {
        List<StockIncomeBill> list = billMapper.selectAll();
        return new PageResult(list.size(),list);
    }

    public List<Stockincome> queryForExport(QueryObject qo) {
        List<Stockincome> list = incomeMapper.queryForExport(qo);
        return list;
    }

    public void update(Stockincome income) {
        incomeMapper.updateByPrimaryKey(income);
    }

    public void insert(Stockincome income) {
        incomeMapper.insert(income);
    }


}
